package com.woniuxy.juc.reentrant;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 可打断的锁
 * <P> Date: 2022/4/8:8:54
 * <P> Description:
 */
@Slf4j(topic = "c.ReentrantLockTest2")
public class ReentrantLockTest2 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            //如果没竞争 获取lock 对象锁
            //如果有竞争进入阻塞队列 可以被其他线程用interrupt打断
            try {
                log.debug("尝试获取锁");
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("没有获取锁 返回");
                return;
            } finally {
                log.debug("解锁");
                lock.unlock();
            }
        }, "t1");



        lock.lock();
        try {
            Sleep.sleep(1000);
            log.debug("打断t1");
            t1.interrupt();
            t1.start();
        } finally {
            lock.unlock();
        }
    }
}
